package com.zhugang.week13.array;

import java.util.Arrays;

/**
 * @program algorithms
 * @description: smallestDifference
 * @author: chanzhugang
 * @create: 2022/09/17 22:21
 */
public class SmallestDifference {

    /**
     * 面试题 16.06 最小差
     * https://leetcode.cn/problems/smallest-difference-lcci/
     *
     * @param a
     * @param b
     * @return
     */
    public int smallestDifference(int[] a, int[] b) {
        // 两个数组：想到双指针，分别指向两个数组
        Arrays.sort(a);
        Arrays.sort(b);
        int i = 0;
        int j = 0;

        long min = Long.MAX_VALUE;
        while (i < a.length && j < b.length) {
            // 小的元素指针向后挪，找更小的
            if (a[i] > b[j]) {
                min = Math.min(min, (long) a[i] - b[j]);
                j++;
            } else {
                min = Math.min(min, (long) b[j] - a[i]);
                i++;
            }
        }
        return (int) min;
    }
}